﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Navigation;
using Project5188.BUS;
using DatePicker = Microsoft.Windows.Controls.DatePicker;

namespace Project5188.Client.ClientCodes
{
    public class SwitchBindingExtension : Binding
    {
        public SwitchBindingExtension()
        {
            Initialize();
        }

        public SwitchBindingExtension(string path)
            : base(path)
        {
            Initialize();
        }

        public SwitchBindingExtension(string path, object valueIfTrue, object valueIfFalse)
            : base(path)
        {
            Initialize();
            ValueIfTrue = valueIfTrue;
            ValueIfFalse = valueIfFalse;
        }

        private void Initialize()
        {
            ValueIfTrue = DoNothing;
            ValueIfFalse = DoNothing;
            Converter = new SwitchConverter(this);
        }

        [ConstructorArgument("valueIfTrue")]
        public object ValueIfTrue { get; set; }

        [ConstructorArgument("valueIfFalse")]
        public object ValueIfFalse { get; set; }

        private class SwitchConverter : IValueConverter
        {
            public SwitchConverter(SwitchBindingExtension switchExtension)
            {
                _switch = switchExtension;
            }

            private readonly SwitchBindingExtension _switch;

            #region IValueConverter Members

            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                try
                {
                    var b = System.Convert.ToBoolean(value);
                    return b ? _switch.ValueIfTrue : _switch.ValueIfFalse;
                }
                catch
                {
                    return DependencyProperty.UnsetValue;
                }
            }

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return DoNothing;
            }

            #endregion
        }

    }

    public class PageBase : Page
    {
        private bool _insertOrUpdate;

        public PageBase()
        {
            
        }

        public PageBase(Extensions.PageNames pageName)
        {
            var screenRoles = new ScreenRoles();
            if (!screenRoles.HasRight((int)pageName, UserInfo.RoleGroupId))
            {
                Loaded += PageBaseLoaded;
            }
        }

        public void GenerateDeleteDialog<T>(DetailView<T> detail, long id)
        {
            if (detail == null) throw new ArgumentNullException("detail");

            const string messageBoxText = "Dikkat! Bu kaydı silmek üzeresiniz. Bu kaydı silmek istediğinizden emin misiniz?";
            const string caption = "Uyarı";
            const MessageBoxButton button = MessageBoxButton.YesNo;
            const MessageBoxImage icon = MessageBoxImage.Warning;

            var result = MessageBox.Show(messageBoxText, caption, button, icon);

            // Process message box results
            switch (result)
            {
                case MessageBoxResult.Yes:
                    detail.Entity = detail.GetEntityById(id)[0];
                    dynamic dynDetail = detail;
                    dynDetail.Entity.IsDeleted = true;
                    dynDetail.Entity.ModifyBy = "System";
                    dynDetail.Entity.ModifyDate = DateTime.Now;
                    dynDetail.Update();
                    Search();
                    break;
            }
        }

        public static bool AreAllValidNumericChars(IEnumerable<char> str)
        {
            return str.All(Char.IsNumber);
        }

        public void BtnCloseClick(object sender, RoutedEventArgs e)
        {
            if (NavigationService != null)
                NavigationService.Navigate(new Uri("/Project5188.Client;component/StartPage.xaml", UriKind.Relative));
        }

        public void BtnClearClick(object sender, RoutedEventArgs e)
        {
            Clear();
        }

        public void Clear()
        {
            var dataGrid = (Grid) FindName("dataGrid");
            if(dataGrid != null)
                for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dataGrid); i++)
                {
                    var dg = VisualTreeHelper.GetChild(dataGrid, i) as DataGrid;
                    if (dg == null) continue;
                    dg.ItemsSource = null;
                }

            var controlsGrid = (Grid)FindName("ControlsGrid");

            if (controlsGrid != null)
                for (var i = 0; i < VisualTreeHelper.GetChildrenCount(controlsGrid); i++)
                {
                    var txt = VisualTreeHelper.GetChild(controlsGrid, i) as TextBox;
                    if (txt == null)
                    {
                        var chkBox = VisualTreeHelper.GetChild(controlsGrid, i) as CheckBox;
                        if (chkBox == null)
                        {
                            var cmb = VisualTreeHelper.GetChild(controlsGrid, i) as ComboBox;
                            if (cmb == null)
                            {
                                var dt = VisualTreeHelper.GetChild(controlsGrid, i) as DatePicker;
                                if (dt != null)
                                {
                                    dt.SelectedDate = null;
                                }
                            }
                            else
                            {
                                cmb.SelectedIndex = 0;
                            }
                        }
                        else
                        {
                            chkBox.IsChecked = false;
                        }
                    }
                    else
                    {
                        txt.Text = String.Empty;
                    }
                }
        }

        public void BtnSearchClick(object sender, RoutedEventArgs e)
        {
            Search();
        }

        public virtual bool Search()
        {
            if (!_insertOrUpdate)
            {
                var controlsGrid = (Grid) FindName("ControlsGrid");

                if (controlsGrid != null)
                    for (var i = 0; i < VisualTreeHelper.GetChildrenCount(controlsGrid); i++)
                    {
                        var txt = VisualTreeHelper.GetChild(controlsGrid, i) as TextBox;
                        if (txt == null)
                        {
                            var chkBox = VisualTreeHelper.GetChild(controlsGrid, i) as CheckBox;
                            if (chkBox == null)
                            {
                                var cmb = VisualTreeHelper.GetChild(controlsGrid, i) as ComboBox;
                                if (cmb == null)
                                {
                                    var dt = VisualTreeHelper.GetChild(controlsGrid, i) as DatePicker;
                                    if (dt != null)
                                    {
                                        if (dt.SelectedDate != null)
                                        {
                                            return true;
                                        }
                                    }
                                }
                                else
                                {
                                    if (cmb.SelectedIndex > -1)
                                    {
                                        return true;
                                    }
                                }
                            }
                            else
                            {
                                return true;
                            }
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(txt.Text) && !String.IsNullOrWhiteSpace(txt.Text))
                            {
                                return true;
                            }
                        }
                    }

                MessageBox.Show("En az bir kriter girmelisiniz!");
                return false;
            }

            _insertOrUpdate = false;
            return false;
        }

        public void InsertClosed(object sender, EventArgs e)
        {
            _insertOrUpdate = true;
            Search();
        }

        public void UpdateClosed(object sender, EventArgs e)
        {
            _insertOrUpdate = true;
            Search();
        }

        void PageBaseLoaded(object sender, EventArgs e) 
        {
            var ns = NavigationService.GetNavigationService(this);
            if (ns != null) ns.Navigate(new Uri("/Project5188.Client;component/ErrorPage.xaml", UriKind.Relative));
        }
    }
}
